import { useEffect } from 'react'
import { matchPath, useLocation, useNavigate } from 'react-router'
import { useSessionStorageState } from 'ahooks'
import { Layout, Menu, theme } from 'antd'
import Icon from '@ant-design/icons'

import { setActiveMenuNamePath } from '../BreadcrumbNav'
import { IMenu, useMenus } from './useMenus'
import { findParentChildPath } from './utils'
import SiderExpandIcon from '@/assets/icons/siderExpand.svg?react'
import styles from './styles.module.less'

export const LeftSider = () => {
  const { token } = theme.useToken()
  const navigate = useNavigate()
  const { pathname } = useLocation()
  const [collapsed, setCollapsed] = useSessionStorageState(`fba_${$APP}_bizLeftSiderCollapsed`, {
    defaultValue: false,
  })
  const { menus, items } = useMenus(!!collapsed)

  const defaultOpenKeys = menus.filter(menu => menu.children).map(({ key }) => key)

  const selectedKeys: string[] = []
  const loop = (menu: IMenu): void => {
    if (menu.children) {
      return menu.children.forEach(loop)
    }
    if (menu.key.startsWith('/')) {
      if (matchPath(menu.pathPattern || menu.key, pathname)) {
        selectedKeys.push(menu.key)
      }
    }
  }
  menus.forEach(loop)

  useEffect(() => {
    let id = requestAnimationFrame(() => {
      id = 0
      document
        .querySelector(`.${styles.box} .ant-menu-item-selected`)
        ?.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
    })
    return () => void (id && cancelAnimationFrame(id))
  }, [pathname])

  const firstKey = selectedKeys[0]
  useEffect(() => {
    if (firstKey) {
      const names = findParentChildPath(menus, firstKey)?.map(d => d.label)
      setActiveMenuNamePath(names ?? null)
    } else {
      setActiveMenuNamePath(null)
    }
    return () => setActiveMenuNamePath(null)
  }, [firstKey, menus])

  return (
    <div className={styles.box}>
      <div className={styles.logo}>
        <img src={`${import.meta.env.VITE_APP_BASE_NAME}/logo.${$APP.toLowerCase()}.jpg`} />
        {!collapsed && <div>{$APP}后台系统</div>}
        {!collapsed && <span style={{ color: token.colorTextTertiary }}>v1.0</span>}
      </div>
      <Layout className={styles.main}>
        <Layout.Sider
          className={styles.sider}
          theme="light"
          collapsible
          collapsedWidth={50}
          collapsed={collapsed}
          onCollapse={setCollapsed}
          trigger={null}
        >
          <Menu
            className={styles.menu}
            mode="inline"
            defaultOpenKeys={collapsed ? undefined : defaultOpenKeys}
            selectedKeys={selectedKeys}
            onClick={({ key }): void => {
              if (key.startsWith('/')) return navigate(key)
              if (/^([a-z][a-z\d+\-.]*:)?\/\/[^/]+/i.test(key)) return void window.open(key, '_blank')
            }}
            items={items}
          />
        </Layout.Sider>
      </Layout>
      <div className={styles.trigger} style={{ color: token.colorTextSecondary }} onClick={() => setCollapsed(v => !v)}>
        <Icon
          style={{
            transform: (collapsed && 'rotate(180deg)') || undefined,
            color: (!collapsed && token.colorTextTertiary) || undefined,
          }}
          component={SiderExpandIcon}
        />
        {!collapsed && <span>收起</span>}
      </div>
    </div>
  )
}
